<template>
  <div class="live-container" ref="liveContent">
    <div class="live-top">
      <div class="header">
        <img src="../assets/img/leftTab.png" alt="" class="leftTab" @click="leftTabBool = true" >
        <p class="title">XLTV1 黄金外汇</p>
        <p class="user">
          <router-link :to="'/login/sign-in?redirect='+location" v-if="user.if_login ===2">登录  |  注册


          </router-link>
          <span v-else>{{user.name}}</span></p>
      </div>
      <div class="video">
        <div v-if="LookBool">
          <div class="maskBox" v-show="leftTabBool||knowledge_pointBool"></div>
          <span v-show="videoType=='VV'&&!(leftTabBool||knowledge_pointBool)" id="_vl_video_component" :pn="vvCode" ls="v20" bt="1"
                lg="http://or5x05smx.bkt.clouddn.com/logo.png" ld="/static/350x350.swf"
                nl="/static/170x170.swf"></span>
          <video v-if="videoType=='YY'" v-show="!(leftTabBool||knowledge_pointBool)" ref="video" x5-video-player-fullscreen="true" autoplay controls preload="auto" webkit-playsinline playsinline x5-video-player-type="">
            <source src="http://hls.yy.com/newlive/10869329_10869329.m3u8?org=yyweb&appid=0&uuid=5f9c5db9b2ab460296d39a44a21fe72f&t=1533109131&tk=e82841200051499cdaa3eb0e3b53d7f6&uid=0&ex_audio=0&ex_coderate=0&ex_spkuid=0">
          </video>
        </div>
      </div>
      <ul class="tab-btn">
        <li v-for="(name, index) in ['讨论区', '今日课表']" @click="tabActive = index"
            :class="{active: tabActive === index}"><span>{{name}}</span></li>
      </ul>
    </div>
    <div class="tab-box" ref="tabBox">
      <div class="tab-con chat-con" v-show="tabActive === 0" ref="chatCon">
        <ul class="chat-list" id="chatPanel" :style="{paddingBottom: face.visible ? '192px' : '52px'}">
          <li v-for="(chat, index) in chatList"
              v-show="Number(chat.show) !== 2 || chat.visitor_id == user.visitor_id || user.group == 'customer'"
              :class="{giftItem: chat.gift, userLv1: chat.role == '0', userKf: chat.role == '1',userVip1:Number(chat.vip_type)===1,userVip2:Number(chat.vip_type)===3,userVip3:Number(chat.vip_type)===4,userVip4:Number(chat.vip_type)===5, dialogueMine: chat.visitor_id == user.visitor_id && chat.type == 'publish' && !chat.gift, dialogueJoin: chat.type == 'login'}">
            <template v-if="chat.type == 'login'">
              <div class="dialogue-join" :class="{joinVIP:Number(chat.if_vip)===1}">
                <span>{{chat.name}}</span>  欢迎来到直播间~
              </div>
            </template>
            <template v-else-if="chat.gift">
              <div class="dialogue-gift">
                {{chat.name}}送了一个礼物 <img :src="chat.gift">
              </div>
            </template>
            <template v-else>
              <div class="chatFace" v-if="!(chat.visitor_id == user.visitor_id && chat.type == 'publish' && !chat.gift)">
                <img :src="chat.face" />
              </div>
              <div class="chatBox">
                <p class="dialogue-name" v-if="!(chat.visitor_id == user.visitor_id && chat.type == 'publish' && !chat.gift)">
                  <em>{{chat.name}}</em>
                  <span>{{chat.date}}</span>
                </p>
                <div class="dialogue-con">
                  <template v-if="chat.type === 'sendbag' || chat.type === 'sendprivatbag'">
                    <div class="dialogue-txt dialogue-redBag">你收到了一个红包，请前往PC端领取</div>
                  </template>
                  <template v-else>
                    <template v-if="chat.image">
                      <div class="dialogue-txt"><img
                        :src="chat.image" class="previewer-img" @click="show(chat.index)"></div>
                    </template>
                    <template v-else>
                      <div class="dialogue-txt" v-html="chat.content"></div>
                    </template>
                  </template>
                </div>
              </div>
              <div class="chatFace" v-if="chat.visitor_id == user.visitor_id && chat.type == 'publish' && !chat.gift">
                <img :src="chat.face" />
              </div>
            </template>
          </li>
        </ul>
        <div class="chat-bottom" ref="chatBottom">
          <div class="chat-input">
            <div class="input">
              <input type="text" v-model="chatTxt" ref="chatInput" @focus="scrollView">
              <i @click="face.visible = !face.visible" ref="faceBtn"></i>
            </div>
            <button @click="sendChat">发送</button>
          </div>
          <ul class="chat-face" v-show="face.visible" ref="facePanel">
            <li v-for="(value, key) in face.list" @click="chooseFace(key)"><img
              :src="value" :title="key"></li>
          </ul>
        </div>
      </div>
      <div class="tab-con tab-class" v-show="tabActive === 1">
        <ul>
          <li class="flex-3" v-for="(item,key) in classList" :class="{active:item.if_line===2}" @click="knowledge_point(item.knowledge_point,item.title)">
            <p>{{item.begin_time + '-' + item.end_time}}</p>
            <p>{{item.title}}</p>
            <p>{{item.coffee_name}}</p>
          </li>
        </ul>
        <div class="class-other" v-if="nowClass">
          <p>直播中</p>
          <p>{{nowClass.begin_time + '-' + nowClass.end_time}}</p>
          <p>{{nowClass.title}}</p>
          <p>{{nowClass.coffee_name}}</p>
        </div>
        <div class="class-other" v-else>
          <p>暂无直播</p>
        </div>
      </div>
    </div>
    <a href="http://wpa.qq.com/msgrd?v=3&uin=3143329170&site=qq&menu=yes" class="gotoQQ" v-show="tabActive === 0">客服</a>
    <a href="http://www.xilongfx.com/clzx/" class="gotoStrategy" v-show="tabActive === 0">观点</a>
    <previewer :list="chatImgList" ref="previewer" :options="options"></previewer>
    <v-pay ref="pay"></v-pay>
    <v-prompting ref="prompting" :look-message="lookData" @fromChildMsg="listenChildMsg"></v-prompting>
    <mt-popup v-model="knowledge_pointBool" pop-transition="popup-fade" class="lessonIntroduction" >
      <img src="../assets/img/close.png" @click="knowledge_pointBool = false" />
      <p class="lessonTitle">{{lessonTitle}}</p>
      <p class="knowledge_points">{{knowledge_points}}</p>
    </mt-popup>
    <mt-popup v-model="leftTabBool" position="left" class="leftTabBox" >
      <ul>
        <li><a href="javascript:;" class="active"><i></i>XLTV1 黄金外汇</a></li>
        <li><a href="/xltv2/m"><i></i>XLTV2 原油期货</a></li>
        <li><a href="/xltv3/m"><i></i>XLTV3 黄金T+D</a></li>
        <li><a href="/xltv4/m"><i></i>XLTV4 VIP专享</a></li>
        <li><a href="http://www.xilongfx.com/clzx/"><i></i>观点中心</a></li>
      </ul>
      <p class="user">
        <router-link :to="'/login/sign-in?redirect='+location" v-if="user.if_login ===2">登录  &nbsp;|  &nbsp;注册</router-link>
        <span v-else @click="logout">退出</span></p>
    </mt-popup>

  </div>
</template>
<script>
  import io from 'socket.io-client'
  import clocker from '../components/clocker'
  import pay from '../components/pay'
  import prompting from '../components/prompting'
  import { Popup } from 'mint-ui'
  import previewer from 'vux/src/components/previewer'

  export default {
    created () {
      const that = this
      this.$http.post('/index/beta_api/seo').then((res) => {
        if(res.code==1) {
          this.shareTitle = res.data.video.seo_title
          document.getElementById('titleId').innerHTML = this.shareTitle
          document.getElementsByName('keywords')[0].setAttribute('content',res.data.video.seo_keyword)
          document.getElementsByName('description')[0].setAttribute('content',res.data.video.seo_description)
        }
      })
      this.socket.on('web_video', function () {
        that.getWebVideoInfo()
      })
      this.socket.on('connect', () => {
        this.$http.post('/index/beta_api/getMobileAll').then(data => {
          this.user = data.user_info
          this.socket.emit('login', this.user.uid, this.user.group,'web','1')
          let chatImgList = this.chatImgList

          console.log('data.chat_list', data.chat_list)
          if (data.chat_list) {
            this.chatList = data.chat_list.map(chat => {
              if (chat.image) {
                chat.index = chatImgList.length
                chatImgList.push({src: chat.image})
              }
              return chat
            }).concat(this.chatList)
          }

          this.classList = data.now_class_list

          console.log('this.nowClass', data.now_class_list)

          for (let i in data.now_class_list) {
            if (Number(data.now_class_list[i].if_line) === 2) {
              this.nowClass = data.now_class_list[i]
              break;
            } else {
              this.nowClass = false
            }
          }

        })
        this.$http.post('/index/purview/look').then((res) => {
          let data = JSON.parse(res)
          if (data.type) {
            this.lookData = data
            switch (data.status) {
              case 4:
              case 5:
              case 6:
                this.LookBool = false
                this.$refs.prompting.visible = true
                break
            }
          }
        })
        this.purviewLook()
        this.videoOnline()
      })
      this.socket.on('new_msg', msg => {
        let data = JSON.parse(msg)
        let chatList = this.chatList
        let chatContent = data.content
        if (chatContent.indexOf("*http")!=-1) {
          chatContent = chatContent.split('*')
          let chatContents = ''
          chatContent.forEach((item, index) => {
            let patt1 = new RegExp("http");
            let result = patt1.test(item);
            if (result) {
              item = '<a class="buleClick" target="_blank" href="' + item + '">' + item + '</a>'
            }
            chatContents += item
          })
          this.$set(data, `content`, chatContents)
        }
        if (data.type === 'check') {
          for (let i = chatList.length - 1; i >= 0; i--) {
            if (chatList[i].chat_id === data.chat_id) {
              if (data.show === 2) {
                chatList.splice(i, 1)
              } else {
                chatList[i].show = 1
                this.scrollToBottom()
              }
              break
            }
          }
        } else {
          if (data.image) {
            let chatImgList = this.chatImgList
            data.index = chatImgList.length
            chatImgList.push({src: data.image})
          }
          chatList.push(data)
        }
      })

      this.socket.on('login_msg', msg => {
        console.log(JSON.parse(msg))
        this.$nextTick(() => {
          this.chatList.push(JSON.parse(msg))
        })
      })
      //切换视频
      this.socket.on('change_vv_code', data => {
        let res = JSON.parse(data)
        if (res.video_id!=1) {
          return
        }
        this.vvCode = res.code
        setTimeout(function () {
          _vl_v._run()
        },200)
      })
      this.initFace()
      this.getWebVideoInfo()
    },
    mounted () {
      document.addEventListener('click', this.handleDocumentClick)
//      this.$refs.video.addEventListener('stalled', () => {
//        alert('error')
//        console.log(this)
//      })
    },
    destroyed () {
      console.log('live destoryed')
      this.socket.close()
      document.removeEventListener('click', this.handleDocumentClick)
    },
    data () {
      return {
        // socket: io('http://111.230.165.69:2120'), //正式
        socket: io('http://111.230.165.69:2130'),//测试
        location: window.location.href,
        tabActive: 0,
        chatList: [],
        classList: [],
        nowClass: {},
        face: {
          list: [],
          visible: false,
        },
        redVisible: false,
        redMoney: '',
        user: {userid: 0},
        chatTxt: '',
        imgBaseUrl: 'http://oxpad4jyo.bkt.clouddn.com/',
        chatImgList: [],
        options: {
          getThumbBoundsFn (index) {
            // find thumbnail element
            let thumbnail = document.querySelectorAll('.previewer-img')[index]
            // get window scroll Y
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            // optionally get horizontal scroll
            // get position of element relative to viewport
            let rect = thumbnail.getBoundingClientRect()
            // w = width
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
            // Good guide on how to get element coordinates:
            // http://javascript.info/tutorial/coordinates
          },
        },
        LookInterval: null,
        LookBool: true,
        lookData: {},
        knowledge_pointBool: false,
        knowledge_points: '',
        lessonTitle: '',
        leftTabBool: false,
        videoType: 'VV',
        liveUrl: '',
        vvCode: '',
      }
    },
    methods: {
      //获得live类型
      getWebVideoInfo () {
        this.$http.post('/index/mobile/getWebVideoInfo').then((res) => {
          let data = JSON.parse(res)
          if (data.code==1) {
            this.videoType = data.data.type
            if(data.data.type=='VV') {
              this.vvCode = data.data.vv_code
              setTimeout(function () {
                _vl_v._run()
              },200)
            } else if (data.data.type=='YY') {
              this.getPlayUrl()
            }
          }
        })
      },
      getPlayUrl () {
        this.$http.post('/index/mobile/getPlayUrl').then((res) => {
          let data = JSON.parse(res)
          if (data.code==1) {
            this.liveUrl = data.data
          } else {
            this.$message('暂无视频!')
          }
        })
      },

      knowledge_point (knowledge_point,title) {
        this.knowledge_points = knowledge_point
        this.lessonTitle = title
        this.knowledge_pointBool = true
      },

      //退出
      logout () {
        this.$http.post('/index/beta_api/logout').then((res) => {
          if (res.code===1) {
            window.location.reload()
            this.$message('退出登录!')
          } else {
            this.$message('退出失败!')
          }

        })
      },

      switchVideoStatus (isPause) {
        if (isPause) {
          this.$refs.video.pause()
//          this.$refs.videoBox.style.height = '1px'
        } else {
          this.$nextTick(() => {
            this.$refs.video.play()
          })
//          this.$refs.videoBox.style.height = 'auto'
        }
      },
      purviewLook () {
        this.LookInterval = setInterval(() => {
          this.$http.post('/index/purview/look').then((res) => {
            let data = JSON.parse(res)
            if (data.type) {
              this.lookData = data
              switch (data.status) {
                case 4:
                case 5:
                case 6:
                  this.LookBool = false
                  this.$refs.prompting.visible = true
                  break
              }
            }
          })
        }, 60 * 1000)
      },
      //定时请求
      videoOnline () {
        setInterval(() => {
          this.$http.post('/index/beta_api/videoOnlineTime').then((res) => {})
        }, 300 * 1000)
      },

      listenChildMsg () {
        this.LookBool = true
        _vl_v._run()
      },
      handleDocumentClick (e) {
        console.log(e)
        if (this.$refs.facePanel.contains(e.target) || this.$refs.faceBtn.contains(e.target)) return
        this.face.visible = false
      },
      scrollView () {
        setTimeout(() => {
          document.body.scrollTop = document.body.scrollHeight
          this.$refs.chatBottom.focus()
        }, 200)
      },
      scrollToBottom () {
        this.$nextTick(() => {
          document.body.scrollTop = document.body.scrollHeight
        })
      },
      initFace () {
        const face = [
          '[微笑]',
          '[嘻嘻]',
          '[哈哈]',
          '[可爱]',
          '[可怜]',
          '[挖鼻]',
          '[吃惊]',
          '[害羞]',
          '[挤眼]',
          '[闭嘴]',
          '[鄙视]',
          '[爱你]',
          '[泪]',
          '[偷笑]',
          '[亲亲]',
          '[生病]',
          '[太开心]',
          '[白眼]',
          '[右哼哼]',
          '[左哼哼]',
          '[嘘]',
          '[衰]',
          '[委屈]',
          '[吐]',
          '[哈欠]',
          '[抱抱]',
          '[怒]',
          '[疑问]',
          '[馋嘴]',
          '[拜拜]',
          '[思考]',
          '[汗]',
          '[困]',
          '[睡]',
          '[钱]',
          '[失望]',
          '[酷]',
          '[色]',
          '[哼]',
          '[鼓掌]',
          '[晕]',
          '[悲伤]',
          '[抓狂]',
          '[黑线]',
          '[阴险]',
          '[怒骂]',
          '[互粉]',
          '[心]',
          '[伤心]',
          '[猪头]',
          '[熊猫]',
          '[兔子]',
          '[ok]',
          '[耶]',
          '[good]',
          '[NO]',
          '[赞]',
          '[来]',
          '[弱]',
          '[草泥马]',
          '[神马]',
          '[囧]',
          '[浮云]',
          '[给力]',
          '[围观]',
          '[威武]',
          '[奥特曼]',
          '[礼物]',
          '[钟]',
          '[话筒]',
          '[蜡烛]',
          '[蛋糕]']
        let tempFace = {}
        for (let i = 0; i < face.length; i++) {
          if (~[10, 15, 23, 26, 55, 58].indexOf(i)) {
            continue
          }
          tempFace[face[i]] = `/static/img/face/${i}.gif`
        }
        this.face.list = tempFace
      },
      chooseFace (key) {
        this.chatTxt += `face${key} `
        // this.faceVisible = false
        // this.$refs.chatTxt.focus()
      },
      sendChat () {
        let content = this.replaceFace(this.chatTxt)
        if (!content) {
          this.$message('请输入内容!')
          return
        }

        let params = {
          visitor_id: this.user.visitor_id,
          content: content,
        }
        this.$http.post('/index/beta_api/sendChat', params).then(data => {
          this.chatTxt = ''
        })
      },
      replaceFace (content) {
        return content.replace(/face\[([^\s\[\]]+?)\]/g, i => {
          let a = i.replace(/^face/g, '')
          return `<img alt="${a}" title="${a}" src="${this.face.list[a]}">`
        })
      },
      show (index) {
        this.$refs.previewer.show(index)
      },
    },
    computed: {
      previewerList () {
        let list = []
        this.chatList.forEach(chat => {
          if (chat.images) {
            list.push({src: chat.images})
          }
        })
        return list
      },
      calcPrice () {
        if (/^[1-9]\d*$/.test(this.payOther)) {
          return this.payOther
        }
        if (this.payPrice > 0) {
          return this.payPrice
        }
        return 0
      },
    },
    components: {
      clocker,
      'mt-popup': Popup,
      previewer,
      'v-pay': pay,
      'v-prompting': prompting,
    },
    watch: {
      chatList () {
        if (this.tabActive === 0) {
          this.scrollToBottom()
        }
      },
      redVisible (val) {
        if (!val) {
          this.redMoney = ''
          this.$nextTick(() => {
            console.log(this.$refs)
            this.$refs.video.play()
          })
        }
      },
    },
  }
</script>
<style>

</style>
